package com.aube.rvi.net;

import com.aube.rvi.module.ParamParser;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * A canned request for retrieving the response body at a given URL as a String.
 */
public class StringRequest extends Request<String> {


    private HashMap<String, String> reqMap;

    public StringRequest(String url, HashMap<String, String> params, ResponseListener<String> listener) {
        super(Method.POST, url, listener);

        params.put("format", "json");
        reqMap = ParamParser.ParserParamsAPI(params);

        setShouldCache(false);
    }

    public StringRequest(String url, ResponseListener<String> listener) {
        super(Method.GET, url, listener);
    }

    public Map<String, String> getHeaders() {
        HashMap<String, String> customizedHeader = new HashMap<String, String>();
        customizedHeader.put("Accept-Encoding", "gzip");
        customizedHeader.put("Connection", "Keep-Alive");
        return customizedHeader;
    }

    public Map<String, String> getParams() {
        return reqMap;
    }

    @Override
    public void deliverResponse(String response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }
}
